Telegram Group & Telegram Channel
🐍 Задача с подвохом: mutable default arguments в Python

🔹 Уровень: Advanced
🔹 Темы: изменяемые аргументы по умолчанию, функции, ловушки с list и dict

📌 Условие

Что выведет следующий код?


def append_to_list(value, my_list=[]):
my_list.append(value)
return my_list

print(append_to_list(1))
print(append_to_list(2))
print(append_to_list(3))


Вопросы

1. Почему результат выглядит неожиданно?
2. Как исправить это поведение?
3. Когда стоит использовать изменяемые аргументы по умолчанию — если вообще стоит?

🔍 Разбор

Ожидаемый вывод:

[1]
[1, 2]
[1, 2, 3]


🔧 Почему так происходит

- Аргументы по умолчанию вычисляются один раз — во время определения функции, а не при каждом вызове.
- Значение my_list=[] создаётся один раз и затем используется повторно при всех вызовах.
- Все вызовы append_to_list изменяют один и тот же список.

⚠️ Подвох

Это один из самых коварных багов в Python, особенно среди начинающих — кажется, что my_list должен быть новым на каждый вызов, но это не так.

🧠 Вывод

- Никогда не используй изменяемые типы (list, dict, set) как значения по умолчанию.
- Вместо этого используй None и создавай новый объект вручную:


def append_to_list(value, my_list=None):
if my_list is None:
my_list = []
my_list.append(value)
return my_list


Тогда вывод будет:

[1]
[2]
[3]


📌 Это правило относится ко всем изменяемым типам: [], {}, set() и кастомные классы.

@Python_Community_ru



tg-me.com/Python_Community_ru/2619
Create:
Last Update:

🐍 Задача с подвохом: mutable default arguments в Python

🔹 Уровень: Advanced
🔹 Темы: изменяемые аргументы по умолчанию, функции, ловушки с list и dict

📌 Условие

Что выведет следующий код?


def append_to_list(value, my_list=[]):
my_list.append(value)
return my_list

print(append_to_list(1))
print(append_to_list(2))
print(append_to_list(3))


Вопросы

1. Почему результат выглядит неожиданно?
2. Как исправить это поведение?
3. Когда стоит использовать изменяемые аргументы по умолчанию — если вообще стоит?

🔍 Разбор

Ожидаемый вывод:

[1]
[1, 2]
[1, 2, 3]


🔧 Почему так происходит

- Аргументы по умолчанию вычисляются один раз — во время определения функции, а не при каждом вызове.
- Значение my_list=[] создаётся один раз и затем используется повторно при всех вызовах.
- Все вызовы append_to_list изменяют один и тот же список.

⚠️ Подвох

Это один из самых коварных багов в Python, особенно среди начинающих — кажется, что my_list должен быть новым на каждый вызов, но это не так.

🧠 Вывод

- Никогда не используй изменяемые типы (list, dict, set) как значения по умолчанию.
- Вместо этого используй None и создавай новый объект вручную:


def append_to_list(value, my_list=None):
if my_list is None:
my_list = []
my_list.append(value)
return my_list


Тогда вывод будет:

[1]
[2]
[3]


📌 Это правило относится ко всем изменяемым типам: [], {}, set() и кастомные классы.

@Python_Community_ru

BY Python Community


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/Python_Community_ru/2619

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

The global forecast for the Asian markets is murky following recent volatility, with crude oil prices providing support in what has been an otherwise tough month. The European markets were down and the U.S. bourses were mixed and flat and the Asian markets figure to split the difference.The TSE finished modestly lower on Friday following losses from the financial shares and property stocks.For the day, the index sank 15.09 points or 0.49 percent to finish at 3,061.35 after trading between 3,057.84 and 3,089.78. Volume was 1.39 billion shares worth 1.30 billion Singapore dollars. There were 285 decliners and 184 gainers.

Telegram and Signal Havens for Right-Wing Extremists

Since the violent storming of Capitol Hill and subsequent ban of former U.S. President Donald Trump from Facebook and Twitter, the removal of Parler from Amazon’s servers, and the de-platforming of incendiary right-wing content, messaging services Telegram and Signal have seen a deluge of new users. In January alone, Telegram reported 90 million new accounts. Its founder, Pavel Durov, described this as “the largest digital migration in human history.” Signal reportedly doubled its user base to 40 million people and became the most downloaded app in 70 countries. The two services rely on encryption to protect the privacy of user communication, which has made them popular with protesters seeking to conceal their identities against repressive governments in places like Belarus, Hong Kong, and Iran. But the same encryption technology has also made them a favored communication tool for criminals and terrorist groups, including al Qaeda and the Islamic State.

Python Community from in


Telegram Python Community
FROM USA